<template>
	<view class="address-edit-page">
		<!-- 顶部导航 -->
		<view class="nav-header">
			<view class="nav-back" @click="goBack">
				<u-icon name="arrow-left" size="20" color="#333"></u-icon>
			</view>
			<text class="nav-title">{{ isEdit ? '编辑地址' : '新增地址' }}</text>
			<view class="nav-right">
				<text v-if="isEdit" class="delete-btn" @click="deleteAddress">删除</text>
			</view>
		</view>
		
		<scroll-view class="form-content" scroll-y>
			<view class="form-section">
				<!-- 收货人 -->
				<view class="form-item" :class="{ error: errors.name }">
					<text class="label required">收货人</text>
					<input 
						class="input" 
						v-model.trim="form.name" 
						placeholder="请输入收货人姓名"
						maxlength="20"
						@blur="validateField('name')"
						@input="clearError('name')"
					/>
				</view>
				<text v-if="errors.name" class="error-text">{{ errors.name }}</text>
				
				<!-- 手机号 -->
				<view class="form-item" :class="{ error: errors.phone }">
					<text class="label required">手机号</text>
					<input 
						class="input" 
						v-model.trim="form.phone" 
						placeholder="请输入手机号"
						type="number"
						maxlength="11"
						@blur="validateField('phone')"
						@input="clearError('phone')"
					/>
				</view>
				<text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
				
				<!-- 所在地区 -->
				<view class="form-item" :class="{ error: errors.region }" @click="showRegionPicker">
					<text class="label required">所在地区</text>
					<view class="region-selector">
						<text class="region-text" :class="{ placeholder: !regionText }">{{ regionText || '请选择省市区' }}</text>
						<u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
					</view>
				</view>
				<text v-if="errors.region" class="error-text">{{ errors.region }}</text>
				
				<!-- 详细地址 -->
				<view class="form-item address-detail" :class="{ error: errors.detail }">
					<text class="label required">详细地址</text>
					<view class="textarea-wrapper">
						<u-textarea 
							:value="form.detail"
							placeholder="请输入详细地址，如街道、楼牌号等"
							:maxlength="200"
							:autoHeight="true"
							:showConfirmBar="false"
							:border="false"
							:customStyle="textareaStyle"
							@blur="validateField('detail')"
							@input="onDetailInput"
							@linechange="onLineChange"
						></u-textarea>
						<text class="char-count">{{ form.detail.length }}/200</text>
					</view>
				</view>
				<text v-if="errors.detail" class="error-text">{{ errors.detail }}</text>
				
				<!-- 设为默认地址 -->
				<view class="form-item default-switch">
					<text class="label">设为默认地址</text>
					<switch 
						:checked="form.isDefault" 
						color="#27B387"
						@change="onDefaultChange"
					/>
				</view>
			</view>
			
			<!-- 位置选择 -->
			<view class="location-section">
				<view class="section-title">
					<u-icon name="map" size="16" color="#27B387"></u-icon>
					<text class="title-text">位置信息</text>
					<text class="optional-text">（可选）</text>
				</view>
				
				<view class="location-item" @click="chooseLocation">
					<view class="location-info">
						<text class="location-name" :class="{ placeholder: !locationInfo.name }">
							{{ locationInfo.name || '点击选择位置' }}
						</text>
						<text class="location-address" v-if="locationInfo.address">{{ locationInfo.address }}</text>
					</view>
					<u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
				</view>
				
				<view v-if="locationInfo.name" class="location-actions">
					<text class="clear-location" @click="clearLocation">清除位置</text>
				</view>
			</view>
		</scroll-view>
		
		<!-- 底部按钮 -->
		<view class="bottom-actions">
			<button class="save-btn" @click="saveAddress" :disabled="!canSave || loading" :class="{ loading }">
				<u-loading-icon v-if="loading" size="16" color="#fff" mode="circle"></u-loading-icon>
				<text class="btn-text">{{ loading ? '保存中...' : '保存' }}</text>
			</button>
		</view>
		
		<!-- 地区选择器 -->
		<u-picker 
			:show="showPicker" 
			mode="region" 
			:default-region="defaultRegion"
			@confirm="onRegionConfirm"
			@cancel="onPickerCancel"
		></u-picker>
	</view>
</template>

<script>
export default {
	data() {
		return {
			isEdit: false,
			addressId: null,
			showPicker: false,
			loading: false,
			
			// 表单数据
			form: {
				name: '',
				phone: '',
				province: '',
				city: '',
				district: '',
				detail: '',
				isDefault: false
			},
			
			// 表单验证错误
			errors: {},
			
			// 默认地区
			defaultRegion: ['北京市', '北京市', '朝阳区'],
			
			// 位置信息
			locationInfo: {
				name: '',
				address: '',
				latitude: null,
				longitude: null
			},
			
			// u-textarea 自定义样式
			textareaStyle: {
				backgroundColor: 'transparent',
				fontSize: '14px',
				color: '#333',
				lineHeight: '1.5',
				minHeight: '60px',
				padding: '0'
			}
		}
	},
	computed: {
		// 地区文本
		regionText() {
			if (this.form.province && this.form.city && this.form.district) {
				return `${this.form.province} ${this.form.city} ${this.form.district}`
			}
			return ''
		},
		
		// 是否可以保存
		canSave() {
			return this.form.name.trim() && 
				   this.form.phone.trim() && 
				   this.form.province && 
				   this.form.city && 
				   this.form.district && 
				   this.form.detail.trim() &&
				   Object.keys(this.errors).length === 0
		}
	},
	onLoad(options) {
		if (options.id) {
			this.isEdit = true
			this.addressId = options.id
			this.loadAddressDetail()
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			if (this.hasChanges()) {
				uni.showModal({
					title: '提示',
					content: '您有未保存的修改，确定要离开吗？',
					success: (res) => {
						if (res.confirm) {
							uni.navigateBack()
						}
					}
				})
			} else {
				uni.navigateBack()
			}
		},
		
		// 检查是否有修改
		hasChanges() {
			// 简单的修改检测逻辑
			return this.form.name || this.form.phone || this.form.detail || this.regionText
		},
		
		// 加载地址详情
		async loadAddressDetail() {
			try {
				uni.showLoading({ title: '加载中...' })
				
				// TODO: 调用地址详情接口
				// const res = await this.$api.getAddressDetail(this.addressId)
				
				// 模拟数据
				await new Promise(resolve => setTimeout(resolve, 500))
				this.form = {
					name: '张三',
					phone: '13888888888',
					province: '北京市',
					city: '北京市',
					district: '朝阳区',
					detail: '三里屯街道工体北路8号院1号楼101室',
					isDefault: true
				}
				
				this.locationInfo = {
					name: '工体北路8号院',
					address: '北京市朝阳区三里屯街道',
					latitude: 39.9163,
					longitude: 116.4432
				}
			} catch (error) {
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		// 字段验证
		validateField(field) {
			this.$nextTick(() => {
				switch (field) {
					case 'name':
						if (!this.form.name.trim()) {
							this.$set(this.errors, 'name', '请输入收货人姓名')
						} else if (this.form.name.length < 2) {
							this.$set(this.errors, 'name', '收货人姓名至少2个字符')
						}
						break
					case 'phone':
						if (!this.form.phone.trim()) {
							this.$set(this.errors, 'phone', '请输入手机号')
						} else if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
							this.$set(this.errors, 'phone', '请输入正确的手机号')
						}
						break
					case 'detail':
						if (!this.form.detail.trim()) {
							this.$set(this.errors, 'detail', '请输入详细地址')
						} else if (this.form.detail.length < 5) {
							this.$set(this.errors, 'detail', '详细地址至少5个字符')
						}
						break
				}
				
				// 验证地区
				if (!this.form.province || !this.form.city || !this.form.district) {
					this.$set(this.errors, 'region', '请选择所在地区')
				}
			})
		},
		
		// 清除错误
		clearError(field) {
			if (this.errors[field]) {
				this.$delete(this.errors, field)
			}
		},
		
		// 显示地区选择器
		showRegionPicker() {
			this.clearError('region')
			this.showPicker = true
		},
		
		// 地区选择确认
		onRegionConfirm(e) {
			const { province, city, area } = e
			this.form.province = province.label
			this.form.city = city.label
			this.form.district = area.label
			this.clearError('region')
			this.showPicker = false
		},
		
		// 地区选择取消
		onPickerCancel() {
			this.showPicker = false
		},
		
		// 默认地址切换
		onDefaultChange(e) {
			this.form.isDefault = e.detail.value
		},
		
		// 选择位置
		chooseLocation() {
			uni.chooseLocation({
				success: res => {
					this.locationInfo = {
						name: res.name,
						address: res.address,
						latitude: res.latitude,
						longitude: res.longitude
					}
					
					// 智能填充详细地址
					if (!this.form.detail && res.name) {
						this.form.detail = res.name
						this.clearError('detail')
					}
				},
				fail: err => {
					console.log('选择位置失败', err)
					if (err.errMsg.includes('cancel')) {
						return // 用户取消，不显示错误
					}
					uni.showToast({
						title: '选择位置失败，请检查定位权限',
						icon: 'none',
						duration: 2000
					})
				}
			})
		},
		
		// 清除位置
		clearLocation() {
			this.locationInfo = {
				name: '',
				address: '',
				latitude: null,
				longitude: null
			}
		},
		
		// 删除地址
		deleteAddress() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个地址吗？',
				confirmColor: '#ff4757',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({ title: '删除中...' })
							
							// TODO: 调用删除地址接口
							// await this.$api.deleteAddress(this.addressId)
							
							await new Promise(resolve => setTimeout(resolve, 500))
							
							uni.hideLoading()
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
							
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						} catch (error) {
							uni.hideLoading()
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 全面验证
		validateAll() {
			this.errors = {}
			
			// 验证收货人
			if (!this.form.name.trim()) {
				this.$set(this.errors, 'name', '请输入收货人姓名')
			} else if (this.form.name.length < 2) {
				this.$set(this.errors, 'name', '收货人姓名至少2个字符')
			}
			
			// 验证手机号
			if (!this.form.phone.trim()) {
				this.$set(this.errors, 'phone', '请输入手机号')
			} else if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
				this.$set(this.errors, 'phone', '请输入正确的手机号')
			}
			
			// 验证地区
			if (!this.form.province || !this.form.city || !this.form.district) {
				this.$set(this.errors, 'region', '请选择所在地区')
			}
			
			// 验证详细地址
			if (!this.form.detail.trim()) {
				this.$set(this.errors, 'detail', '请输入详细地址')
			} else if (this.form.detail.length < 5) {
				this.$set(this.errors, 'detail', '详细地址至少5个字符')
			}
			
			return Object.keys(this.errors).length === 0
		},
		
		// u-textarea 输入事件
		onDetailInput(value) {
			this.form.detail = value
			this.clearError('detail')
		},
		
		// u-textarea 行数变化事件
		onLineChange(e) {
			// 可以在这里处理行数变化的逻辑
			console.log('行数变化:', e)
		},
		
		// 保存地址
		async saveAddress() {
			if (!this.validateAll()) {
				uni.showToast({
					title: '请完善地址信息',
					icon: 'none'
				})
				return
			}
			
			this.loading = true
			
			try {
				const addressData = {
					...this.form,
					...this.locationInfo
				}
				
				// TODO: 调用保存地址接口
				// if (this.isEdit) {
				//     await this.$api.updateAddress(this.addressId, addressData)
				// } else {
				//     await this.$api.createAddress(addressData)
				// }
				
				await new Promise(resolve => setTimeout(resolve, 1000))
				
				uni.showToast({
					title: this.isEdit ? '修改成功' : '添加成功',
					icon: 'success'
				})
				
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} catch (error) {
				console.error('保存地址失败:', error)
				uni.showToast({
					title: '保存失败，请重试',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.address-edit-page {
	background-color: #f5f5f5;
	height: 100vh;
	display: flex;
	flex-direction: column;
}

.nav-header {
	height: 44px;
	background-color: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 15px;
	border-bottom: 1px solid #f0f0f0;
	position: relative;
	z-index: 10;
	
	.nav-back {
		padding: 5px;
		border-radius: 50%;
		transition: background-color 0.2s;
		
		&:active {
			background-color: #f0f0f0;
		}
	}
	
	.nav-title {
		font-size: 16px;
		font-weight: 500;
		color: #333;
	}
	
	.nav-right {
		width: 60px;
		display: flex;
		justify-content: flex-end;
		
		.delete-btn {
			font-size: 14px;
			color: #ff4757;
			padding: 5px 8px;
			border-radius: 4px;
			transition: background-color 0.2s;
			
			&:active {
				background-color: rgba(255, 71, 87, 0.1);
			}
		}
	}
}

.form-content {
	flex: 1;
	padding: 10px 0;
	
	.form-section {
		background-color: #fff;
		margin: 0 15px 15px;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
		
		.form-item {
			padding: 15px;
			border-bottom: 1px solid #f0f0f0;
			display: flex;
			align-items: center;
			position: relative;
			transition: background-color 0.2s;
			
			&:last-child {
				border-bottom: none;
			}
			
			&.error {
				background-color: rgba(255, 71, 87, 0.02);
				border-left: 3px solid #ff4757;
			}
			
			&.address-detail {
				align-items: flex-start;
				flex-direction: column;
				
				.label {
					margin-bottom: 8px;
					align-self: flex-start;
				}
				
				.textarea-wrapper {
					width: 100%;
					position: relative;
					min-height: 60px;
				}
				
				.char-count {
					position: absolute;
					bottom: 8px;
					right: 8px;
					font-size: 12px;
					color: #999;
					background-color: rgba(255, 255, 255, 0.9);
					padding: 2px 4px;
					border-radius: 2px;
					z-index: 2;
				}
			}
			
			&.default-switch {
				justify-content: space-between;
			}
			
			.label {
				width: 80px;
				font-size: 14px;
				color: #333;
				flex-shrink: 0;
				
				&.required::after {
					content: '*';
					color: #ff4757;
					margin-left: 2px;
				}
			}
			
			.input {
				flex: 1;
				font-size: 14px;
				color: #333;
				border: none;
				outline: none;
				background: transparent;
				
				&::placeholder {
					color: #ccc;
				}
				
				&:focus {
					color: #27B387;
				}
			}
			
			.textarea {
				flex: 1;
				font-size: 14px;
				color: #333;
				min-height: 60px;
				line-height: 1.5;
				border: none;
				outline: none;
				background: transparent;
				resize: none;
				
				&::placeholder {
					color: #ccc;
				}
				
				&:focus {
					color: #27B387;
				}
			}
			
			.region-selector {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 8px 0;
				
				.region-text {
					font-size: 14px;
					color: #333;
					
					&.placeholder {
						color: #ccc;
					}
				}
			}
		}
		
		.error-text {
			font-size: 12px;
			color: #ff4757;
			padding: 0 15px 10px;
			margin-top: -5px;
			animation: slideDown 0.3s ease;
		}
	}
	
	.location-section {
		background-color: #fff;
		margin: 0 15px;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
		
		.section-title {
			padding: 15px;
			border-bottom: 1px solid #f0f0f0;
			display: flex;
			align-items: center;
			gap: 8px;
			background: linear-gradient(135deg, rgba(39, 179, 135, 0.05) 0%, rgba(39, 179, 135, 0.02) 100%);
			
			.title-text {
				font-size: 14px;
				color: #333;
				font-weight: 500;
			}
			
			.optional-text {
				font-size: 12px;
				color: #999;
				margin-left: auto;
			}
		}
		
		.location-item {
			padding: 15px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			transition: background-color 0.2s;
			
			&:active {
				background-color: #f8f9fa;
			}
			
			.location-info {
				flex: 1;
				
				.location-name {
					font-size: 14px;
					color: #333;
					display: block;
					margin-bottom: 4px;
					
					&.placeholder {
						color: #ccc;
					}
				}
				
				.location-address {
					font-size: 12px;
					color: #999;
					display: block;
				}
			}
		}
		
		.location-actions {
			padding: 0 15px 15px;
			display: flex;
			justify-content: flex-end;
			
			.clear-location {
				font-size: 12px;
				color: #999;
				padding: 4px 8px;
				border-radius: 4px;
				transition: all 0.2s;
				
				&:active {
					background-color: #f0f0f0;
					color: #666;
				}
			}
		}
	}
}

.bottom-actions {
	height: 80px;
	background-color: #fff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	align-items: center;
	padding: 0 15px;
	position: relative;
	z-index: 10;
	
	.save-btn {
		flex: 1;
		height: 44px;
		background: linear-gradient(135deg, #27B387 0%, #1e9c6f 100%);
		border: none;
		border-radius: 22px;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
		transition: all 0.3s;
		box-shadow: 0 2px 8px rgba(39, 179, 135, 0.3);
		
		&:not(:disabled):active {
			transform: translateY(1px);
			box-shadow: 0 1px 4px rgba(39, 179, 135, 0.4);
		}
		
		&:disabled {
			background: #ccc;
			opacity: 0.6;
			box-shadow: none;
			transform: none;
		}
		
		&.loading {
			pointer-events: none;
		}
		
		.btn-text {
			font-size: 16px;
			color: #fff;
			font-weight: 500;
		}
	}
}

// 动画效果
@keyframes slideDown {
	from {
		opacity: 0;
		transform: translateY(-10px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

// 响应式适配
@media screen and (max-width: 375px) {
	.form-content .form-section .form-item {
		padding: 12px;
		
		.label {
			width: 70px;
			font-size: 13px;
		}
		
		.input, .textarea {
			font-size: 13px;
		}
	}
	
	.nav-header {
		padding: 0 12px;
		
		.nav-title {
			font-size: 15px;
		}
	}
	
	.bottom-actions {
		padding: 0 12px;
		
		.save-btn {
			height: 40px;
			
			.btn-text {
				font-size: 15px;
			}
		}
	}
}

// 深色模式适配（如果需要）
@media (prefers-color-scheme: dark) {
	.address-edit-page {
		background-color: #1a1a1a;
	}
	
	.nav-header, .form-section, .location-section, .bottom-actions {
		background-color: #2d2d2d;
		border-color: #404040;
	}
	
	.nav-title, .label, .input, .textarea, .region-text, .location-name {
		color: #fff;
	}
	
	.location-address, .char-count, .optional-text {
		color: #999;
	}
	
	.form-item.error {
		background-color: rgba(255, 71, 87, 0.1);
	}
}
</style>